package com.hualan.servlet;

import com.alibaba.fastjson.JSON;
import com.hualan.bean.PanghuCommunity;
import com.hualan.dao.CommunityDao;
import com.hualan.dao.impl.CommunityDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

@WebServlet("/communityListServlet")
public class CommunityListServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        //1.获取前端传递的分页信息 page size
        String pageString = req.getParameter("page");
        int page = pageString == null ? 1 : Integer.parseInt(pageString);
        String sizeString = req.getParameter("size");
        int size = sizeString == null ? 10 : Integer.parseInt(sizeString);
        //2.创建map对象 用来给前端返回信息 创建Dao对象来进行操作
        HashMap<String, Object> map = new HashMap<>();
        CommunityDao communityDao = new CommunityDaoImpl();
        //3.分页查询数据
        List<PanghuCommunity> communities = communityDao.selectCommunityByPage(page,size);
        //将数据存储到键值对中
        map.put("list",communities);
        //4.设置状态码
        if (communities != null){
            map.put("code",200);
            map.put("message","请求成功");
        }else {
            map.put("code",300);
            map.put("message","请求失败");
        }
        //5.将数据返回到前端
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().write(JSON.toJSONString(map));
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
